import java.net.InetAddress;
import java.net.UnknownHostException;


public class Packet {
	
	//COSTANTI DELLA CLASSE 
	final int indexIPD = 3;
	final int indexPD = 5;
	final int indexIPS = 9;
	final int indexPS = 11;
	final int indexIDPa = 13;
	final int indexL = 15;
	
	//ATTRIBUTI DELLA CLASSE 
	private InetAddress IPDestination;
	private int portDestination;
	private InetAddress IPSource;
	private int portSource;
	private int IDPacket;
	private byte[] data;
	private int dataLength;
	
	//METODI COSTRUTTORE
	public Packet (InetAddress IPDestination, int portDestination, InetAddress IPSource, int portSource, int IDPacket, byte[] data ){
		this.IPDestination = IPDestination;
		this.portDestination = portDestination;
		this.IPSource = IPSource;
		this.portSource = portSource;
		this.IDPacket = IDPacket;
		this.data = data;
		this.dataLength = data.length;
	}
	
	public Packet (byte[] pkt) throws UnknownHostException {
		byte[] IP = new byte[4];
		
		IP[0] = pkt[0];
		IP[1] = pkt[1];
		IP[2] = pkt[2];
		IP[3] = pkt[3];
		this.IPDestination = InetAddress.getByAddress(IP);
 		this.portDestination = ((int)pkt[4]+128)*256+(int)pkt[5]+128;
 		IP[0] = pkt[6];
		IP[1] = pkt[7];
		IP[2] = pkt[8];
		IP[3] = pkt[9];
		this.IPSource = InetAddress.getByAddress(IP);
		this.portSource = ((int)pkt[10]+128)*256+(int)pkt[11]+128;
		this.IDPacket = ((int)pkt[12]+128)*256+(int)pkt[13]+128;
		this.dataLength = ((int)pkt[14]+128)*256+(int)pkt[15]+128;
		this.data = new byte[this.dataLength];
		for (int i = 0; i < this.dataLength; i++)
			this.data[i] = pkt[i+16]; 
	}
	
	//METODI DELLA CLASSE 
	public InetAddress getIPDestination() {
		return this.IPDestination;
	}
	
	public int getPortDestination() {
		return this.portDestination;
	}
	
	public InetAddress getIPSource() {
		return this.IPSource;
	}
	
	public int getPortSource() {
		return this.portSource;
	}
	
	public int getIDPacket() {
		return this.IDPacket;
	}
	
	public byte[] getData() {
		return this.data;
	}
	
	public int getLength() {
		return this.dataLength;
	}
	
	public byte[] toByte() {
		byte[] byteString = new byte[16+this.data.length];
		for (int i = 0; i <= this.indexIPD; i++)
			byteString[i] = this.IPDestination.getAddress()[i];

		byteString[this.indexPD-1] = (byte)(this.portDestination / 256 -128);
		byteString[this.indexPD] = (byte)(this.portDestination % 256 -128);
		
		for (int i = 0 ; i <= 3; i++)
			byteString[indexPD+1+i] = this.IPDestination.getAddress()[i];
		
		byteString[this.indexPS-1] = (byte)(this.portSource / 256 - 128); 
		byteString[this.indexPS] = (byte)(this.portSource % 256 - 128);
		
		byteString[this.indexIDPa-1] = (byte)(this.IDPacket / 256 - 128);
		byteString[this.indexIDPa] = (byte)(this.IDPacket % 256 - 128);
		
		byteString[indexL-1] = (byte)(this.dataLength / 256 -128);
		byteString[indexL] = (byte)(this.dataLength % 256 -128);
	
		for (int i = 0; i < this.data.length; i++) 
			byteString[this.indexL+1+i] = this.data[i];
		
		return byteString;
		
	}

}
